<template>
    <div>
       
               <!--    查询功能-->
                   <div class="center">
                <div class="profile" >
       <el-input style="width: 200px;" v-model="studyQueryVo.value"
       @keyup.enter.native="getStudyBookByDemand()" ref="myInput"
       placeholder="请输入关键字搜索"></el-input>
         <el-button
            type="primary"
             style="margin-left: 5px; height: 31.5px"
            icon="el-icon-search"
            @click="getStudyBookByDemand()"
            >查询</el-button>

        </div>


        <div class="xxzlselect" style="margin-bottom: 5px; display: flex;">
            <!-- 下拉框父类型查询 -->
            <el-select v-model="studyQueryVo.parentTypeId" placeholder="请选择父类型" 
            @change="set_one_class(studyQueryVo.parentTypeId)" readonly>
                <el-option v-for="item in options" :key="item.parentId" :label="item.pname"
                    :value="item.parentId"></el-option>
            </el-select>                           
            <!--    下拉框子类型查询-->
            <el-select v-model="studyQueryVo.typeId" placeholder="请选择子类型" 
            @change="set_two_class(studyQueryVo.typeId)" readonly>
                <el-option v-for="item in twoSelect" :key="item.id" :label="item.name"
                 :value="item.id"></el-option>
            </el-select>
            
            <!--      重置按钮-->
            <el-button style="height: 32px;margin-left: 5px;" type="danger" @click="resetSelect()">重置</el-button>
        </div>
        <!-- 新增学习资料按钮 -->
        <el-button @click="mod(1)" style="height: 32px;margin-left: 5px; position: absolute;right: 212px;" type="success">新增</el-button>
    </div>
        <!--    列表展示-->
        <el-table :data="StudyData" :header-cell-style="{ background: '#D3D3D3FF', color: '#555555' }">
            <el-table-column prop="typeId" label="id" width="200" header-align="center"> </el-table-column>
            <!-- <el-table-column prop="userName" label="用户名称" width="80"></el-table-column> -->
            <el-table-column prop="parentTypeName" label="资料父类型" width="100">
                <!-- <template slot-scope="scope">
                    {{ getPostParentTypeName(scope.row.parentTypeId) }}
                </template> -->
            </el-table-column>
            <el-table-column prop="typeName" label="资料类型" width="100">
                <!-- <template slot-scope="scope">
                    {{ getPostTypeName(scope.row.parentTypeId, scope.row.typeId) }}
                </template> -->
            </el-table-column>
            <el-table-column prop="title" label="资料标题" width="100">
            </el-table-column>
            <!-- <el-table-column label="轮播图" width="150" header-align="center">
                <template slot-scope="scope">
                    <el-image style="width: 150px; height: 50px" :src="scope.row.image" fit="contain"
                        :preview-src-list="[scope.row.postImage]"></el-image>
                </template>
            </el-table-column> -->
            <el-table-column prop="description" label="介绍" width="200" header-align="center"></el-table-column>
            <el-table-column prop="isPrivate" label="是否公开" width="80">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.isPrivate === false ? 'success' : 'danger'" disable-transitions>{{
                        scope.row.isPrivate === false ? "已公开" : "未公开" }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="gmtCreate" label="创建时间" width="140">
            </el-table-column>
            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red"
                        title="确定删除此学习资料吗？" @confirm=" deleteStudyData(scope.row.id)" style="margin-left: 5px">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                    <a target="_blank" :href="scope.row.fileUrl"><el-button size="small" style="margin-left: 5px;"  type="primary">查看</el-button></a>
                </template>
            </el-table-column>
        </el-table>

        
        <el-dialog title="学习资料信息" :visible.sync="centerDialogVisible" width="30%" center :before-close="handleClose">
      
      <el-form ref="form" :rules="rules" :model="StudyInfo" label-width="120px">
       
        <el-form-item  label="仅社团可见">
      <el-switch v-model="StudyInfo.isPrivate" />
    </el-form-item>


    <el-form-item style="width: 100%;" label="标题" prop="title">
       <el-input  v-model="StudyInfo.title"></el-input>
   </el-form-item>



   <el-form-item label="简介" prop="description">
       <el-input  type="textarea" v-model="StudyInfo.description"></el-input>
   </el-form-item>

        <el-form-item label="父类型" prop="oneclass">
            <el-select v-model="StudyInfo.parentTypeId" placeholder="请选择父类型" 
            @change="setTwoClassForEdit(StudyInfo.parentTypeId,1)" readonly>
                <el-option v-for="item in options" :key="item.parentId" :label="item.pname"
                    :value="item.parentId"></el-option>
            </el-select>                           
        </el-form-item>

        <el-form-item label="子类型" prop="twoclass">
             <!--    下拉框子类型查询-->
             <el-select v-model="StudyInfo.typeId" placeholder="请选择子类型"  readonly>
                <el-option v-for="item in twoSClassForEdit" :key="item.id" :label="item.name"
                 :value="item.id"></el-option>
            </el-select>
        </el-form-item>

       
        <el-form-item label="文件上传" >
             <el-select v-model="uploadType" placeholder="请选择上传类型"  readonly>
                <el-option  label="本地文件"
                 :value="1"></el-option>

                 <el-option  label="网络地址"
                 :value="2"></el-option>

            </el-select>
        </el-form-item>

        <el-form-item v-show="uploadType === 1" label="本地文件" >
          
          <el-upload
           :on-remove="handleRemove"
          :on-success="handleSuccess"
                class="upload-demo"
              :action="actionUrl"
                multiple
                :data="uploadData"
            name="file"
            :headers="headers"
              :limit="1"
              :file-list="fileList"
                >
                    <el-button size="small" type="primary">点击上传</el-button>
</el-upload>
        </el-form-item>

        <div v-if="onloadfile === 1" style="height: 18px;">

           
        </div>

        <el-form-item  v-show="uploadType === 2" style="width: 100%;" label="网络地址" >
       <el-input   v-model="StudyInfo.fileUrl"></el-input>
   </el-form-item>

  

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </span>
    </el-dialog>



           <!-- 分页  -->
        <div class="pagination-wrapper">
            <div class="pagination-container">
                <el-pagination @size-change="onSizeChange" @current-change="onCurrentChange"
                    :current-page="page" :page-sizes="[5, 10, 20, 30]" :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
import { getStudyBook , getAllStudyType ,deleteStudyDataById,editStudyData,newStudyBook} from "@/api/studyServices"
// import { getPost, delPost } from "@/api/q&aService/postManagement";
// import { firstLevelPostQuery } from "@/api/q&aService/postTypeManagement/firstLevelPostQuery"
// import { queryParentId } from "@/api/q&aService/postTypeManagement/queryParentId"
// import { del } from "vue";
// import { set } from "core-js/core/dict";

export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: "xxzlManagement",
    data() {
        return {
            onloadfile:1,
            twoSClassForEdit:{},
            fileList: [],
            StudyInfo: {
               
                "description": "",
                "fileUrl": "",
                "id": "",
                "isPrivate": false,
                "parentTypeId": "",
                "parentTypeName": "",
                "title": "",
                "typeId": "",
                "typeName": "",
            },
            uploadType: 1,
            headers: {},
            uploadData: {
        bucketName: 'study' // 上传头像时的附加参数
      },
            actionUrl: "http://42.194.233.38:8222/minioservice/minio-upload/upload",// 服务器上传API地址
            form: {
        id: "",
        name: "",
        parentId: "",
      },

    //         rules: {
    //     name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    //     parentId: [{ required: true, trigger: "blur" }],
    //     title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    //     description: [{ required: true, message: "请输入简介", trigger: "blur" }],
    //     oneclass: [{ required: true, message: "请选择父类", trigger: "blur" }],
    //     twoclass: [{ required: true, message: "请选择子类", trigger: "blur" }],
    //     sort: [{ required: true, trigger: "blur" }],
    //   },
            centerDialogVisible: false,
            twoSelect:[],
            searchTypeOne: "",
            one_class: "",
            two_class: "",
            types: [],
            options: [],

        studytypequeryVo: {
                parentId: '',
                // 设置 typeId 为一个空数组，符合子类型集合的要求
                typeId: [],
                description: '',
                gmtCreate: '',
                gmtModified: '',
                 id: '',
                 isDeleted: false,
                 name: ''
             },

      studytypepage: 1,
      // 每页查询的数量，初始化为10
      studytypelimit: 50,

            // sumpage: 0,
            StudyData: [],

            studyPage: 1,
         // 学习资料分页
        studyLimit: 5,
         // 学习资料每页显示数量
        studyQueryVo: {
            isPrivate: '',
            parentTypeId:'',
             typeId: '',
             value: ''
         },

            // postAll: [],//所有帖子
            // parentPostTypeAll: [],//父类型
            // postSonType: [],//子类型
            // querySonsType: [],//下拉框的子类型
            // queryPostParams: {
            //     ptypeId: "",//搜索的父类型id
            //     typeId: "",//搜索的子类型id
            // },
            // id:'',
            // page: 1,
            // limit: 5,
            total: 0,
        };
    },
    watch: {
        fileList(newList) {
            if (newList.length > 1) {
                this.fileList = [newList[1]];
            }
        }
     
    },
    methods: {

        resetData(){
            this.StudyInfo =  {
               
               "description": "",
               "fileUrl": "",
               "id": "",
               "isPrivate": false,
               "parentTypeId": "",
               "parentTypeName": "",
               "title": "",
               "typeId": "",
               "typeName": "",
           };
        },

        newStudyBookone(){
            newStudyBook(this.StudyInfo).then((res) => {
              
                if (res.code === 20000) {
                    this.$message({
                        message: "新增成功",
                        type: "success",
                    });
                    this.centerDialogVisible = false;
                    this.getStudyBookByDemand()
                } else {
                    this.$message({
                        message: "新增失败",
                        type: "error",
                    });
                }
            });
        },

 //修改
 async doMod() {
        await this.editStudyDataById(this.id, this.StudyInfo);
        }

,
async doSave() {
        await this.newStudyBookone();
            },
    //提交数据到后台
    save() {
        this.fileList= [],
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.id) {
            //如果有id则修改
            this.doMod();
          } else {
            //否则增加
            this.doSave();
          }
        } else {
          this.$message({
            message: "表单数据有误",
            type: "error",
          });
          return false;
        }
      });
    },



        editStudyDataById(id,StudyInfo){
            editStudyData(id,StudyInfo).then((res) => {
                if (res.code === 20000) {
                    this.centerDialogVisible = false;
                    this.$message({
                        message: "编辑成功",
                        type: "success",
                    });
                    this.getStudyBookByDemand()
                } else {
                    this.$message({
                        message: "编辑失败",
                        type: "error",
                    });
                }
            });
        },

         // 从 cookie 中获取 token
    getTokenFromCookie() {
      const cookies = document.cookie.split('; ');
      const token = cookies.find(row => row.startsWith('token='))?.split('=')[1];
      return token;
    },
    // 设置 headers
    setHeaders() {
      this.headers = {
        'token': this.getTokenFromCookie()
      };
    },

    handleRemove(){
        this.StudyInfo.fileUrl =""
        this.onloadfile=1
    },

        handleSuccess(res) {
      if (res.success) {
        this.onloadfile=2
        this.$message.success('上传成功');
        this.StudyInfo.fileUrl = res.data.url
        // this.fileList.res.data;
      } else {
        this.$message.error('上传失败');
      }
    },

        onSizeChange(val) {
            this.studyLimit = val;
            this.getStudyBookByDemand();
        },
        onCurrentChange(val) {
            this.studyPage = val;
            this.StudyData = [];
            this.getStudyBookone();
        },

        //删除学习资料
        deleteStudyData(id){
            console.log('调用了删除函数','id=',id);
            deleteStudyDataById(id).then((res) => {
                if (res.code === 20000) {
                    this.$message({ 
                        message: "删除成功",
                        type: "success",
                    });
                    this.getStudyBookByDemand()
                } else {
                    this.$message({
                        message: "删除失败",
                        type: "error",
                    });}})},
        //获取学习资料类型
        getAllStudy() {
     getAllStudyType().then((res) => {
         this.options=res.tree;
         console.log(this.options);
      
     }); 
   },
     //获取学习资料列表
     getStudyBookone() {
        getStudyBook(this.studyPage, this.studyLimit, this.studyQueryVo).then((res) => {
        this.StudyData = [...this.StudyData,...res.list.records];
        this.pages = res.list.current;
        this.total = res.list.total;
        }).catch((err) => { console.log(err,'获取学习资料列表失败'); });
        },

    getStudyBookByDemand(){
    this.loading = true;
    this.StudyData = [];
    this.studyPage = 1;
    this.getStudyBookone();
    this.loading = false;
  },

  
  getTwoClassForEdit(hh) {
      let arr = this.options.filter((item) => item.parentId === hh);
     
        return arr && arr[0] ? arr[0].studyTypeList : [];
      
    },
    setTwoClassForEdit(hh,ee){
        if(ee===1){
            this.StudyInfo.typeId = "";}
        this.twoSClassForEdit= this.getTwoClassForEdit(hh)
  },


  getTwoClass(hh) {
      let arr = this.options.filter((item) => item.parentId === this.one_class);
      if (hh===1) {
        console.log('hh===1');
        return []
      }else{
        console.log('hh!==1');

        return arr && arr[0] ? arr[0].studyTypeList : [];
      }
    },
    
        //重置下拉框
        resetSelect() {
            this.twoSelect=this.getTwoClass(1);
            this.StudyData = [];
            this.studyQueryVo.parentTypeId = '';
            this.studyQueryVo.typeId = '';
            this.getStudyBookByDemand();
        },


  set_two_class(value) {
    this.studyQueryVo.value = "";
      this.two_class = value; 
      this.studyQueryVo.typeId=this.two_class
      this.getStudyBookByDemand();
    },
    set_one_class(value) {
    this.one_class = value;
        this.twoSelect= this.getTwoClass();
        console.log(this.twoSelect,'this.twoSelect');
         this.studyQueryVo.value = "";
      
      this.two_class = "";
      this.studyQueryVo.parentTypeId = value;
      this.studyQueryVo.typeId = '';
      this.getStudyBookByDemand();
    },

    mod(row) {
        if(row===1){this.resetData();this.id='';}
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        //赋值到表单
        this.id = row.id;
        this. StudyInfo.id = row.id;
        this. StudyInfo.title = row.title;
        this. StudyInfo.description = row.description;
        if(row!==1){this.StudyInfo.isPrivate = row.isPrivate;}
        this. StudyInfo.fileUrl = row.fileUrl;
        this. StudyInfo.typeId = row.typeId;
        this. StudyInfo.parentTypeId = row.parentTypeId;
        this. StudyInfo.parentTypeName = row.parentTypeName;
        this. StudyInfo.typeName = row.typeName;
        this.setTwoClassForEdit(row.parentTypeId)

      });
    },
    
        handleClose(done) {
            this.$confirm("确认关闭？")
                .then(() => {
                    done();
                })
                .catch(() => { });
        },
      
    },
    mounted() {

            this.$refs.myInput.focus();
            this.setHeaders();
        // this.queryPsot();
        
        // this.queryParentType();
    },
    created() {
        
        this.getAllStudy();
        this.getStudyBookone();
    }
};
</script>

<style scoped>
    .center {    
        position: relative;
        display: flex;
        justify-content: flex-start;
    }
    .profile {
        margin-left: 2px;
        margin-bottom: 5px;
        display: flex;
        width: 100%;
        background-color: #fff;
        color: #505050;
        font-size: 18px;
    }
    .xxzlselect{
        position: relative;
        right: 550px;
    }
    a {
    text-decoration: none; /* 移除下划线 */
    color: white; /* 设置颜色为黑色 */
}
.upload-btn:hover{
    border:  1px dashed #409eff;
}
</style>